package com.ddy.test.creditcardmanage

import android.content.Intent
import android.os.Bundle
import com.google.android.material.navigation.NavigationView
import androidx.core.view.GravityCompat
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.*
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TableLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import com.ddy.test.creditcardmanage.R.id.cardListView
import com.ddy.test.creditcardmanage.common.Constant
import com.ddy.test.creditcardmanage.model.Card
import com.ddy.test.creditcardmanage.model.CardViewModel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
        title = "MyCards"

//        fab.setOnClickListener {
//            startActivity(Intent(this, AddCard().javaClass))

            // 打开第三方应用的某个页面
//            var intent = Intent(Intent.ACTION_MAIN)
//            intent.addCategory(Intent.CATEGORY_LAUNCHER)
//            val activityName = "com.ddy.test.kotlintest.MainTest"
//            intent.component = ComponentName("com.ddy.test.kotlintest",activityName)
//            startActivity(intent)

//            打开第三方应用
//            val activityName = "com.ddy.test.kotlintest"
//            val intent = packageManager.getLaunchIntentForPackage(activityName)
//            if (intent != null) {
//                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                startActivity(intent)
//            }
//        }

        val toggle = ActionBarDrawerToggle(
                this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)

        val allCards = CardViewModel(this.application).getAllCards()
        allCards.observe(this, Observer {
            showCards(it)
        })
    }

    private fun showCards(cards: List<Card>) {
        if(cards.isEmpty()){
            Log.w("Main", "not added card")

            val cardList = findViewById<LinearLayout>(cardListView)
            cardList.addView(LayoutInflater.from(this).inflate(R.layout.card_lists_null, cardList, false))
        }else{
            val sortedCards: List<Card> = sortByCurrentDate(cards)
            val table = findViewById<LinearLayout>(cardListView)
            table.removeAllViewsInLayout()
            for(card in sortedCards){
                val row = LayoutInflater.from(this).inflate(R.layout.card_info_table_row, table, false)
                val cardBaseView = row.findViewById<TextView>(R.id.cardBase)
                val cardBaseString = (if(card.comment == "") "未备注信息" else card.comment) + "\n" +
                        card.cardNo +  "\n" +
                        card.permanentLine + "\n" +
                        card.temporaryLine
                cardBaseView.text = cardBaseString

                val cardLineView = row.findViewById<TextView>(R.id.cardLine)
                cardLineView.text = card.statementAmount.toString()

                val cardDateView = row.findViewById<TextView>(R.id.cardDate)
                val cardDateString = "" + card.statementDate + "\n" + card.dueDate.toString()
                cardDateView.text = cardDateString

                row.findViewWithTag<LinearLayout>(Constant.SWIPE_DELETE_ROW).setOnClickListener {
                    startActivity(Intent(this, CardRecordsActivity().javaClass)
                        .putExtra("cardId", card.id)
                        .putExtra("cardName", card.comment))
                }

                row.findViewWithTag<Button>(Constant.SWIPE_DELETE_ROW_BUTTON).setOnClickListener {
                    val cardViewModel = CardViewModel(this.application)
                    Log.w(CardRecordsActivity.LOG_TAG, "delete card " + card.id)
                    val builder = AlertDialog.Builder(this).create()

                    builder.setCancelable(true)
                    builder.setTitle("确认删除" + card.comment + "?")

                    builder.setMessage("删除后会一起删除该卡片下所有的交易记录")
                    builder.setButton(AlertDialog.BUTTON_POSITIVE, "确定") { _, _ ->
                        cardViewModel.deleteCard(card.id)
                        table.removeView(row)
                    }

                    builder.setButton(AlertDialog.BUTTON_NEGATIVE, "取消") { dialog, _ ->
                        dialog.cancel()
                    }

                    builder.show()
                }
                row.findViewWithTag<Button>(Constant.SWIPE_MODIFY_ROW_BUTTON).setOnClickListener {
                    startActivity(Intent(this, ModifyCard().javaClass).putExtra("cardId", card.id))
                }

                table.addView(row)
            }

        }
    }

    private fun sortByCurrentDate(cards: List<Card>): List<Card> {
        val cardsBefore = ArrayList<Card>()
        val cardsAfter = ArrayList<Card>()
        val sortedCard = ArrayList<Card>()
        val dayOfMonth = java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH)
        for(card in cards){
            if(card.statementDate >= dayOfMonth){
                cardsAfter.add(card)
            }else{
                cardsBefore.add(card)
            }
        }
        sortedCard.addAll(cardsBefore)
        sortedCard.addAll(cardsAfter)
        return sortedCard
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_add_card -> {
                startActivity(Intent(this, AddCard().javaClass))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_camera -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_manage -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }
}
